package com.ruoyi.school.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.FileTypeEnum;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.school.convert.PacAcademicOutputParticipationConverter;
import com.ruoyi.school.domain.*;
import com.ruoyi.school.domain.vo.AcademicOutputParticipationListVo;
import com.ruoyi.school.enums.AuditTypeEnum;
import com.ruoyi.school.service.*;
import com.ruoyi.school.mapper.PacAcademicOutputParticipationMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author jeremylin
 * @description 针对表【pac_academic_output_participation(学术成果参与表)】的数据库操作Service实现
 * @createDate 2025-07-10 08:52:56
 */
@Service
public class PacAcademicOutputParticipationServiceImpl extends ServiceImpl<PacAcademicOutputParticipationMapper, PacAcademicOutputParticipation>
        implements PacAcademicOutputParticipationService {

    @Resource
    private StudentService studentService;

    @Resource
    private PacTeacherService pacTeacherService;

    @Resource
    private PacAuditRecordsService pacAuditRecordsService;

    @Resource
    private AcademicOutputService academicOutputService;

    /**
     * 参与
     *
     * @param pacAcademicOutput
     * @return
     */
    @Override
    public boolean join(PacAcademicOutputParticipation pacAcademicOutput) {
        validateJoin(pacAcademicOutput);
        // 插入学生信息
        Long stuId = pacAcademicOutput.getParticipantId();
        Student student = studentService.getById(stuId);
        pacAcademicOutput.setParticipantName(student.getStuName());
        pacAcademicOutput.setParticipantNum(student.getStuNum());
        pacAcademicOutput.setParticipantArea(student.getSmallTeam());

        PacTeacher pacTeacher = pacTeacherService.getAcademicTeacherInfo(student.getClassId());
        if (pacTeacher != null) {
            pacAcademicOutput.setAcademicTeacherId(pacTeacher.getId().longValue());
        }

        if (Objects.nonNull(pacAcademicOutput.getAcFile())) {
            FileTypeEnum fileTypeName = FileTypeUtils.getFileTypeName(pacAcademicOutput.getAcFile());
            pacAcademicOutput.setAcFileType(fileTypeName.getCode());
        }

        save(pacAcademicOutput);

        return true;
    }

    private void validateJoin(PacAcademicOutputParticipation pacAcademicOutput) {
        if (pacAcademicOutput.getParticipantId() == null) {
            throw new BaseException("请选择参与学生");
        }

        if (pacAcademicOutput.getOutputId() == null) {
            throw new BaseException("参与成果不能为空");
        }

        Long participantId = pacAcademicOutput.getParticipantId();

        PacAcademicOutput pacActualOutput = new PacAcademicOutput();
        pacActualOutput.setId(pacAcademicOutput.getOutputId());

        PacAcademicOutput details = academicOutputService.getDetails(pacActualOutput);

        if (details.getAcAudit().equals(2)) {
            throw new BaseException("该成果已审核通过,无法加入");
        }

        pacActualOutput.setStuId(pacAcademicOutput.getParticipantId());

        if (details.getStuId().equals(participantId)) {
            throw new BaseException("无法参与自己的成果");
        }

        PacAcademicOutputParticipation one = lambdaQuery()
                .eq(PacAcademicOutputParticipation::getParticipantId, participantId)
                .eq(PacAcademicOutputParticipation::getOutputId, pacAcademicOutput.getOutputId())
                .one();

        if (Objects.nonNull(one)) {
            throw new BaseException("已参与该成果");
        }

        Long count = lambdaQuery().eq(PacAcademicOutputParticipation::getOutputId, pacAcademicOutput.getOutputId()).count();
        pacAcademicOutput.setJoinIndex((int) (count + 1));
    }

    /**
     * 获取参与人员
     *
     * @param pacActualOutputId
     * @return
     */
    @Override
    public List<AcademicOutputParticipationListVo> getParticipants(Long pacActualOutputId) {
        List<PacAcademicOutputParticipation> list = lambdaQuery().eq(PacAcademicOutputParticipation::getOutputId, pacActualOutputId).list();
        Map<Long, PacAcademicOutputParticipation> listMap = list.stream().collect(Collectors.toMap(PacAcademicOutputParticipation::getParticipantId, Function.identity()));

        List<Long> collect = list.stream().map(PacAcademicOutputParticipation::getParticipantId).collect(Collectors.toList());
        List<Student> sysUsers = studentService.selectByStuIds(collect);
        List<AcademicOutputParticipationListVo> vos = PacAcademicOutputParticipationConverter.INSTANCE.student2Vo(sysUsers);
        vos.forEach(item -> {
            PacAcademicOutputParticipation pacActualOutputParticipation = listMap.get(item.getId().longValue());
            if (pacActualOutputParticipation != null) {
                item.setStatus(pacActualOutputParticipation.getStatus());
                item.setJoinId(pacActualOutputParticipation.getId());
            }
        });
        return vos;
    }

    /**
     * 删除参与人员
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        if (id == null) {
            throw new RuntimeException("id不能为空");
        }
        removeById(id);
        // 同时删除审批
        // 同时删除审批记录
        pacAuditRecordsService.deleteByOutPutId(id, AuditTypeEnum.PAC_WALL_TYPE_ACADEMIC.getCode());
    }

    /**
     * 获取详情
     *
     * @param id
     * @return
     */
    @Override
    public PacAcademicOutputParticipation details(Long id) {
        PacAcademicOutputParticipation one = lambdaQuery().eq(PacAcademicOutputParticipation::getId, id).one();
        return one;
    }

    /**
     * 通过审核的数量
     *
     * @return
     */
    @Override
    public long countByAudit() {
        long count = lambdaQuery().eq(PacAcademicOutputParticipation::getStatus, 2).count();
        return count;
    }

    /**
     * 将参与人员弄成参与状态
     *
     * @param id
     */
    @Override
    public void updateParticipantState(Long id) {
        boolean update = update(new UpdateWrapper<PacAcademicOutputParticipation>()
                .eq("output_id", id)
                .set("status", 2));

    }

    /**
     * 查询团队成员ids
     *
     * @param id
     * @return
     */
    @Override
    public List<Long> selectMemberIds(Long id) {
        List<PacAcademicOutputParticipation> list = lambdaQuery().eq(PacAcademicOutputParticipation::getOutputId, id).list();
        if (list != null && list.size() > 0) {
            return list.stream().map(PacAcademicOutputParticipation::getParticipantId).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 删除参与人员
     *
     * @param id
     */
    @Override
    public void deleteByOutPutId(Long id) {
        remove(new LambdaUpdateWrapper<PacAcademicOutputParticipation>().eq(PacAcademicOutputParticipation::getOutputId, id));
    }
}




